package spindles.api.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

public class Util {

	public Util() {
		
	}
	
	public static String nvl(Object obj, String s){
		if(obj == null){
			return s;
		}
		return obj.toString();
	}
	
	public static <T> void add(Collection<T> col, T value, int times){
		for(int i = 0; i < times; i++){
			col.add(value);
		}
	}
	
	public static boolean isEmpty(String text){
		if(text == null){
			return true;
		}
		
		if(text.trim().equals("")){
			return true;
		}
		
		return false;
	}
	
	public static Date addSeconds(Date date, double sec){
		int millis = (int)(sec * 1000);
		return DateUtils.addMilliseconds(date, millis);
	}
	
	public static double subtract(Date lhs, Date rhs){
		long millis = lhs.getTime() - rhs.getTime();
		return (double)millis/1000d;
	}
	
	public static Date join(Date date, Date time){
		Date init = DateUtils.truncate(time, Calendar.DAY_OF_MONTH); //1970
		
		long millis = time.getTime() - init.getTime();
		
		Date day = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
		
		return DateUtils.addMilliseconds(day, (int)millis);
	}
	
	public static Date parseDate(String text, DateFormat[] parsers) throws UserException{		
		for(DateFormat df : parsers){
			try {
				return df.parse(text);
			} catch (ParseException e) {
				continue;
			}
		}
		throw new UserException(ErrorMessages.DATE_UNEXPECTED_FORMAT);
	}
	
	public static String concat(String[] strings, String delim){
		StringBuilder result = new StringBuilder();
		for(String s : strings){
			result.append(s);
			result.append(delim);
		}
		
		return result.toString();
	}
	
	public static Date toDate(String date, String pattern){
		SimpleDateFormat df = new SimpleDateFormat(pattern);		
		try {
			return df.parse(date);
		} catch (ParseException e) {
			throw new ApplicationException(e);
		}
	}
	

}
